<script setup>
import { Message, Iphone, Lock, Key } from '@element-plus/icons-vue'
import { nextTick, ref } from 'vue'
import { useAuthStore } from '@/stores/modules/auth'
import { useSettingsStore } from '@/stores/modules/settings'
import { ElMessage } from 'element-plus'
import { sendVerificationCode, updateEmail, updatePassword, resetPasswordWithCode } from '@/services/userService'
import { useRouter } from 'vue-router'
const authStore = useAuthStore()
const settingsStore = useSettingsStore()
const router = useRouter()
const email = ref(authStore.user.email)
// 处理邮箱
const formatEmail = (email) => {
  // 分割用户名和域名
  const [username, domain] = email.split('@')

  // 处理无效邮箱格式（无 @ 符号）
  if (!domain) return email

  // 生成掩码用户名：前3位 + 6个星号
  const maskedUsername = username.slice(0, 3) + '******'

  // 组合结果
  return `${maskedUsername}@${domain}`
}

const form = ref({
  email: '',
  verifyCode: '',
  newPassword: '',
  oldPassword: '',
  confirmPassword: ''
})

const dialogVisible = ref(false)
const dialogTitle = ref('email')
// 统一操作函数
const toggleDialog = (type) => {
  form.value = {
    email: '',
    verifyCode: '',
    newPassword: '',
    oldPassword: '',
    confirmPassword: ''
  }
  dialogVisible.value = true
  dialogTitle.value = type === 'email' ? '更换邮箱' : '修改密码'
}

// 添加忘记密码模式状态
const isForgetMode = ref(false)

// 切换忘记密码模式
const toggleForgetMode = () => {
  isForgetMode.value = !isForgetMode.value
  // 重置表单
  form.value = {
    email: email.value, // 使用当前邮箱
    verifyCode: '',
    newPassword: '',
    oldPassword: '',
    confirmPassword: ''
  }
}

// 提交表单
const handleSubmit = async () => {
  if (dialogTitle.value === '更换邮箱') {
    return await submitEmailChange()
  } else if (dialogTitle.value === '修改密码') {
    if (isForgetMode.value) {
      return await submitResetPassword()
    } else {
      return await submitPasswordChange()
    }
  }
}

// 添加域名选项数组
const domainOptions = ref([
  { label: 'qq.com', value: 'qq.com' },
  { label: 'gmail.com', value: 'gmail.com' },
  { label: 'outlook.com', value: 'outlook.com' },
  { label: '163.com', value: '163.com' },
  { label: '126.com', value: '126.com' },
  { label: 'foxmail.com', value: 'foxmail.com' },
  { label: 'hotmail.com', value: 'hotmail.com' },
  { label: 'yahoo.com', value: 'yahoo.com' },
  { label: '其他...', value: 'custom' }
])

// 添加邮箱用户名和域名部分
const emailUsername = ref('')
const emailDomain = ref(domainOptions.value[0].value)
const customDomain = ref('')
const isCustomDomain = ref(false)

// 修改 sendVerifyCode 函数
const sendVerifyCode = async () => {
  if (countdown.value > 0) return

  // 构建完整邮箱
  const completeEmail = isCustomDomain.value
    ? `${emailUsername.value}@${customDomain.value}`
    : `${emailUsername.value}@${emailDomain.value}`

  // 验证邮箱格式
  if (!emailUsername.value) {
    ElMessage.error('请输入邮箱用户名')
    return
  }

  if (isCustomDomain.value && !customDomain.value) {
    ElMessage.error('请输入邮箱域名')
    return
  }

  // 检查新邮箱是否与当前邮箱相同
  if (completeEmail === email.value) {
    ElMessage.warning('新邮箱与当前邮箱相同，无需更改')
    return
  }

  loading.value = true
  try {
    const response = await sendVerificationCode(completeEmail)

    if (response && response.success) {
      ElMessage.success('验证码已发送')
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }
  } catch (error) {
    ElMessage.error(error.message || error.response?.data?.message || '发送验证码失败')
  } finally {
    loading.value = false
  }
}

// 修改 submitEmailChange 函数
const submitEmailChange = async () => {
  // 构建完整邮箱
  const completeEmail = isCustomDomain.value
    ? `${emailUsername.value}@${customDomain.value}`
    : `${emailUsername.value}@${emailDomain.value}`

  // 验证表单
  if (!emailUsername.value) {
    ElMessage.error('请输入邮箱用户名')
    return
  }

  if (isCustomDomain.value && !customDomain.value) {
    ElMessage.error('请输入邮箱域名')
    return
  }

  if (!form.value.verifyCode) {
    ElMessage.error('请输入验证码')
    return
  }

  // 检查新邮箱是否与当前邮箱相同
  if (completeEmail === email.value) {
    ElMessage.warning('新邮箱与当前邮箱相同，无需更改')
    return
  }

  try {
    const response = await updateEmail(completeEmail, form.value.verifyCode)

    // 增加调试日志
    console.log('邮箱更新响应:', response)

    // 检查响应结构
    if (response && response.success) {
      ElMessage.success('邮箱更新成功')
      // 更新本地状态
      email.value = completeEmail

      // 确保响应中有用户信息再更新
      if (response.data && response.data.user) {
        const auth = JSON.parse(localStorage.getItem('auth'))
        auth.user = response.data.user
        localStorage.setItem('auth', JSON.stringify(auth))
      }

      dialogVisible.value = false
    } else {
      // 请求成功但业务失败的情况
      ElMessage.error(response?.message || '邮箱更新未成功，请重试')
    }
  } catch (error) {
    console.error('邮箱更新出错:', error)
    // 使用我们添加的自定义消息或后备消息
    ElMessage.error(
      error.customMessage || error.message || error.response?.data?.message || '更新邮箱失败'
    )
  }
}

// 提交密码修改
const submitPasswordChange = async () => {
  // 验证表单
  form.value.oldPassword = form.value.oldPassword.trim()
  form.value.newPassword = form.value.newPassword.trim()
  form.value.confirmPassword = form.value.confirmPassword.trim()

  if (!form.value.oldPassword) {
    ElMessage.error('请输入当前密码')
    return
  }

  if (!form.value.newPassword) {
    ElMessage.error('请输入新密码')
    return
  }

  if (form.value.newPassword !== form.value.confirmPassword) {
    ElMessage.error('新密码与确认密码不一致')
    return
  }

  try {
    const response = await updatePassword(form.value.oldPassword, form.value.newPassword)
    if (response && response.success) {
      ElMessage.success('密码更新成功')
      dialogVisible.value = false
      // 密码更新成功后退出登录,并刷新页面
      await nextTick()
      authStore.logout()
      settingsStore.closeSettingDialog()
      router.push('/login')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '更新密码失败')
  }
}

const handleCancel = () => {
  form.value = {
    email: '',
    verifyCode: '',
    newPassword: '',
    oldPassword: '',
    confirmPassword: ''
  }
  dialogVisible.value = false
}

// 验证码倒计时
const countdown = ref(0)
const loading = ref(false)

// 处理域名变更
const handleDomainChange = () => {
  isCustomDomain.value = emailDomain.value === 'custom'
}

// 发送重置密码验证码
const sendResetPasswordCode = async () => {
  if (countdown.value > 0) return

  loading.value = true
  try {
    // 发送到当前用户的邮箱并明确指定类型为密码重置
    const response = await sendVerificationCode(email.value, 'reset-password')

    if (response && response.success) {
      ElMessage.success('验证码已发送到您的邮箱')
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }
  } catch (error) {
    ElMessage.error(error.customMessage || error.message || '发送验证码失败')
  } finally {
    loading.value = false
  }
}

// 新增: 通过验证码重置密码
const submitResetPassword = async () => {
  // 验证表单
  form.value.newPassword = form.value.newPassword.trim()
  form.value.confirmPassword = form.value.confirmPassword.trim()
  form.value.verifyCode = form.value.verifyCode.trim()

  if (!form.value.verifyCode) {
    ElMessage.error('请输入验证码')
    return
  }

  if (!form.value.newPassword) {
    ElMessage.error('请输入新密码')
    return
  }

  if (form.value.newPassword !== form.value.confirmPassword) {
    ElMessage.error('新密码与确认密码不一致')
    return
  }

  try {
    const response = await resetPasswordWithCode(email.value, form.value.verifyCode, form.value.newPassword)

    if (response && response.success) {
      ElMessage.success('密码重置成功')
      dialogVisible.value = false
      isForgetMode.value = false
    }
  } catch (error) {
    ElMessage.error(error.customMessage || error.message || error.response?.data?.message || '密码重置失败')
  }
}
</script>

<template>
  <div class="setting-section">
    <h3>账户绑定</h3>
    <div class="account-settings">
      <!-- 邮箱 -->
      <div class="account-item">
        <div class="item-header">
          <div class="item-title">
            <el-icon>
              <Message />
            </el-icon>
            <span>邮箱</span>
          </div>
          <el-tag type="success" size="small" effect="plain">已绑定</el-tag>
        </div>
        <div class="item-content">
          <span class="hint-text">{{ formatEmail(email) }}</span>
          <el-button link type="primary" size="small" @click="toggleDialog('email')"
            >更换邮箱</el-button
          >
        </div>
      </div>

      <!-- 账户密码 -->
      <div class="account-item">
        <div class="item-header">
          <div class="item-title">
            <el-icon>
              <Lock />
            </el-icon>
            <span>密码</span>
          </div>
          <el-tag type="success" size="small" effect="plain">已设置</el-tag>
        </div>
        <div class="item-content">
          <span class="hint-text">已设置，可通过账户密码登录</span>
          <el-button link type="primary" size="small" @click="toggleDialog('password')"
            >修改密码</el-button
          >
        </div>
      </div>
    </div>
  </div>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" class="theme-adaptive-dialog" width="40%">
    <el-form :model="form" label-width="120px" v-if="dialogTitle == '更换邮箱'">
      <el-form-item label="新邮箱" class="email-input">
        <div class="email-input-container">
          <el-input
            v-model="emailUsername"
            placeholder="请输入用户名"
            style="width: 150px"
          />
          <span class="email-at">@</span>
          <el-select
            v-model="emailDomain"
            style="width: 140px; background:var(--el-fill-color-light)"
            @change="handleDomainChange">
            <el-option
              style="background: var(--el-fill-color-light)"
              v-for="option in domainOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </div>
      </el-form-item>

      <!-- 自定义域名输入框，仅当选择"其他..."时显示 -->
      <el-form-item label="" v-if="isCustomDomain" class="email-custom-domain">
        <div class="email-input-container" style="margin-left: 120px;">
          <el-input
            v-model="customDomain"
            placeholder="请输入邮箱"
            style="width: 294px"
          />
        </div>
      </el-form-item>

      <el-form-item label="验证码" prop="verifyCode">
        <div class="verify-code-container">
          <el-input v-model="form.verifyCode" placeholder="请输入验证码" minlength="6" maxlength="6" style="width: 200px" />
          <el-button type="primary" :disabled="countdown > 0 || loading" @click="sendVerifyCode">
            {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
          </el-button>
        </div>
      </el-form-item>
    </el-form>

    <el-form :model="form" label-width="120px" v-if="dialogTitle === '修改密码' && !isForgetMode">
      <el-form-item label="当前密码">
        <el-input v-model="form.oldPassword" type="password" show-password style="width: 160px" />
      </el-form-item>

      <el-form-item label="新密码">
        <el-input v-model="form.newPassword" type="password" show-password style="width: 160px" />
      </el-form-item>

      <el-form-item label="确认密码">
        <el-input
          v-model="form.confirmPassword"
          type="password"
          show-password
          style="width: 160px"
        />
      </el-form-item>

      <div class="forget-password-link">
        <el-button type="text" @click="toggleForgetMode">忘记密码？</el-button>
      </div>
    </el-form>

    <!-- 忘记密码模式表单 -->
    <el-form :model="form" label-width="120px" v-if="dialogTitle === '修改密码' && isForgetMode">
      <el-form-item label="邮箱验证码">
        <div class="verify-code-container">
          <el-input v-model="form.verifyCode" placeholder="请输入验证码" style="width: 160px" />
          <el-button
            type="primary"
            :disabled="countdown > 0 || loading"
            @click="sendResetPasswordCode">
            {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
          </el-button>
        </div>
      </el-form-item>

      <el-form-item label="新密码">
        <el-input v-model="form.newPassword" type="password" show-password style="width: 160px" />
      </el-form-item>

      <el-form-item label="确认密码">
        <el-input
          v-model="form.confirmPassword"
          type="password"
          show-password
          style="width: 160px"
        />
      </el-form-item>

      <div class="forget-password-link">
        <el-button type="text" @click="toggleForgetMode">返回修改密码</el-button>
      </div>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="handleSubmit" class="save-button">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
/* 原有样式保持scoped */
.setting-section {
  margin-bottom: 32px;
}

.setting-section h3 {
  margin: 0 0 16px;
  font-size: 16px;
  font-weight: 500;
  color: var(--color-text);
}

.account-settings {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.account-item {
  padding: 20px;
  border-radius: 8px;
  background-color: var(--el-fill-color-light);
  transition: all 0.3s;
}

.item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.item-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

.item-title .el-icon {
  font-size: 18px;
}

.item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: var(--el-text-color-regular);
}

.hint-text {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

:deep(.el-tag) {
  border-radius: 4px;
}

:deep(.el-tag--success) {
  --el-tag-bg-color: var(--el-color-success-light-9);
  --el-tag-border-color: var(--el-color-success-light-5);
  --el-tag-text-color: var(--el-color-success);
}

:deep(.el-tag--warning) {
  --el-tag-bg-color: var(--el-color-warning-light-9);
  --el-tag-border-color: var(--el-color-warning-light-5);
  --el-tag-text-color: var(--el-color-warning);
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}

:deep(.el-form-item__label) {
  color: var(--el-text-color-regular);
}

:deep(.el-input__wrapper) {
  background-color: var(--el-fill-color-light);
}

:deep(.el-input__inner) {
  color: var(--el-text-color-regular);
}

:deep(.el-select__wrapper) {
  background-color: var(--el-fill-color-light) !important;
}

/* 对话框样式不使用scoped，提高优先级 */

/* 修改对话框样式为使用主题变量 */


.cancel-button,
.save-button {
  background: transparent;
  border: none;
  color: var(--el-button-save-text-color);
}

.cancel-button {
  color: var(--el-button-cancel-text-color);
}

.cancel-button:hover {
  background: var(--el-button-cancel-hover-color);
  color: var(--el-button-cancel-hover-text-color) !important;
}

.save-button:hover {
  background: var(--el-button-save-hover-color);
  color: var(--el-button-save-hover-text-color);
}
.verify-code-container {
  display: flex;
  align-items: center;
  gap: 20px;
}

.forget-password-link {
  text-align: right;
  margin-top: -10px;
  margin-bottom: 10px;
}

.forget-password-link .el-button {
  font-size: 13px;
  padding: 0;
  color: var(--el-color-primary);
}

.forget-password-link .el-button:hover {
  color: var(--el-color-primary-light-3);
  text-decoration: underline;
}

.email-input-container {
  display: flex;
  align-items: center;
  gap: 5px;
}

.email-at {
  font-size: 16px;
  color: var(--el-text-color-regular);
  margin: 0 2px;
}

.email-custom-domain {
  margin-top: -10px;
}
:deep(.el-select .el-input__wrapper) {
  background: var(--el-fill-color-light) !important;
  box-shadow: none !important;
}

</style>


<style>
.theme-adaptive-dialog .el-dialog {
  background-color: var(--el-bg-color-overlay) !important;
  box-shadow: var(--el-box-shadow) !important;
}

.theme-adaptive-dialog .el-dialog__header {
  background-color: transparent !important;
  margin: 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.theme-adaptive-dialog .el-dialog__body {
  background-color: transparent !important;
  padding: 20px 0 !important;
}

.theme-adaptive-dialog .el-dialog__footer {
  background-color: transparent !important;
}
.theme-adaptive-dialog .el-input__wrapper {
  background-color: var(--el-fill-color-light);
}
.dialog-footer {
  text-align: right;
}
</style>
